package com.ng.job.command;

import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.ng.job.entity.ScheduleJobEntity;
import com.ng.job.service.ScheduleJobService;
import com.ng.job.utils.ScheduleUtils;

/**
 * 启动后初始化扫描当前定时任务列表，确定要初始化的定时任务监听
 * @author lyf
 *
 */
@Component
@Order(2)
public class StartRun implements CommandLineRunner{
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private Scheduler scheduler;
	
	@Autowired
	private ScheduleJobService jobService ;
	
	@Override
	public void run(String... args) throws Exception {
		logger.info("start run schedule job ");
		
		List<ScheduleJobEntity> scheduleJobList = jobService.list();
		for(ScheduleJobEntity scheduleJob : scheduleJobList){
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
		}
		
	}
 
	
}
